import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        //这里放全局参数
        currentUser: JSON.parse(localStorage.getItem('chhuangboot.currentUser') || '{}'), //从localStorage获取
    },
    mutations: {
        //这里是set方法
        setCurrentUser:(state, user)=>{
            if(user){
                state.currentUser = user;
                //把登录的用户信息保存到localStorage中，防止页面刷新，导致vuex重新启动丢失
                localStorage.setItem('chhuangboot.currentUser', JSON.stringify(user));
                localStorage.setItem('chhuangboot.token', user.token);
            }else{//删除
                state.currentUser = {};
                localStorage.removeItem('chhuangboot.currentUser');
                localStorage.removeItem('chhuangboot.token');
            }
        }
    },
    getters: {
        //这里是get方法   
        getCurrentUser:(state) => state.currentUser
    },
    actions: {
        //这个部分我暂时用不上

    },
    modules: {
        //这里是我自己理解的是为了给全局变量分组，所以需要写提前声明其他store文件，然后引入这里

    }
});

export default store;